#pragma once
#include<iostream>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include<string.h>
#include<unistd.h>
#include<string.h>
using namespace std;
const int backlog=5;
class sock
{
public:
void Socket()
{

sockfd_=socket(AF_INET,SOCK_STREAM,0);
if(sockfd_<0)
{
  cout<<"网络套接字创建失败"<<endl;
  exit(0);

}
cout<<"网络套接字创建成功"<<endl;

}
void Bind(uint16_t port)
{
  struct sockaddr_in client;
  memset(&client,0,sizeof(client));
  client.sin_family=AF_INET;
  client.sin_addr.s_addr=INADDR_ANY;
  client.sin_port=htons(port);
  if(bind(sockfd_,(const sockaddr*)&client,sizeof(client))<0)
     {
      cout<<"绑定失败"<<endl;
      exit(0);
     }
       cout<<"绑定成功"<<endl;
}
void Listen()
{
  if(listen(sockfd_,backlog)<0)
    {
     cout<<"监听失败"<<endl;
     exit(0);
    }
     cout<<"监听成功"<<endl;
}
int Accept(uint16_t *clientport,string *clientip)
{
 struct sockaddr_in peer;
 socklen_t len=sizeof(peer);
 int newfd=accept(sockfd_,(sockaddr*)&peer,&len);
 if(newfd<0)
 {
   cout<<"accept error"<<endl;
   exit(0);
 }
 char ipstr[64];
 inet_ntop(AF_INET,&peer.sin_addr,ipstr,sizeof(ipstr));
 *clientip=ipstr;
 *clientport=ntohs(peer.sin_port);
 cout<<"clientip:"<<*clientip<<"clientport:"<<*clientport<<endl;
 return newfd;
 
}

bool Connect(uint16_t clientport,string clientip)
{
  struct sockaddr_in client;
  memset(&client,0,sizeof(client));
  client.sin_family=AF_INET;
  client.sin_port=htons(clientport);
  inet_pton(AF_INET,clientip.c_str(),&client.sin_addr);


  int n=connect(sockfd_,(const sockaddr*)&client,sizeof(client));
  if(n==-1)
  {
   cout<<"connect to "<<clientip<<":"<<clientport<<endl;
   return false;
  }
  return true;
 
}
void Close(int fd)
{
  close(fd);
}
int fd()
{

return sockfd_;


}



public:

int sockfd_;
};